package cn.darkhorse.jpush.service.impl;

import cn.darkhorse.alarm.pojo.AlarmParameterSettings;
import cn.darkhorse.alarm.service.AlarmParameterSettingsService;
import cn.darkhorse.common.config.MesJPushConfig;
import cn.darkhorse.device.pojo.MesDevice;
import cn.darkhorse.device.service.MesDeviceService;
import cn.darkhorse.jpush.dao.JPushDao;
import cn.darkhorse.jpush.service.JPushService;
import cn.darkhorse.jpush.vo.JPushVO;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.report.ReceivedsResult;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class JPushServiceImpl implements JPushService {
    protected static final Logger LOG = LoggerFactory.getLogger(JPushServiceImpl.class);
    @Resource
    private JPushDao jPushDao;
    @Resource
    private AlarmParameterSettingsService parameterSettingsService;
    @Resource
    private MesDeviceService mesDeviceService;
    /**
     * 绑定用户与设备唯一识别码
     *
     * @param userid
     * @param registrationID
     * @return
     */
    @Override
    public boolean updaeteregistrationIDByUser(Long userid, String registrationID) {
        boolean result=jPushDao.updaeteregistrationIDByUser(userid,registrationID);
        return result;
    }

    /**
     * 极光APP推送
     *
     * @return
     */
    @Override
    public String sendMsg(String registrationId,String content,String title,Map<String, String> extras) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MesJPushConfig.getMasterSecret(), MesJPushConfig.getAppKey(), null, clientConfig);
        PushPayload payload=buildPushObject_android_and_ios(registrationId,content,title,extras);
        String code="";
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            System.out.println(result);
            System.out.println("registrationId:"+registrationId);
            System.out.println("msg_id:"+result.msg_id);
            code= "ok";
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());
            code=e.getMessage();
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. " , e);
            LOG.error("HTTP Status: " + e.getStatus());
            LOG.error("Error Code: " + e.getErrorCode());
            LOG.error("Error Message: " + e.getErrorMessage());
            LOG.error("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
            code= String.valueOf(e.getErrorCode());
        }
        return code;

    }

    /**
     * @return
     */
    @Override
    public List<JPushVO> getJPushSendMsg() {
        List<JPushVO> sendMsg = jPushDao.getSendMsg();
        if(null!=sendMsg&&sendMsg.size()>0){
            Map<Long, AlarmParameterSettings> parameterSettingsMap=parameterSettingsService.getMap(null);
            Map<Long, MesDevice> deviceMap=mesDeviceService.list().stream().collect(Collectors.toMap(MesDevice::getId, Function.identity()));
            sendMsg.forEach(item->{
                if(deviceMap.containsKey(item.getDeviceId())){
                    MesDevice device=deviceMap.get(item.getDeviceId());
                    if("default".equals(device.getCode())){
                        item.setDeviceName(device.getName());
                    }else{
                        item.setDeviceName(device.getName()+"-"+device.getCode());
                    }
                }
                if(parameterSettingsMap.containsKey(item.getParameterId())){
                    AlarmParameterSettings settings=parameterSettingsMap.get(item.getParameterId());
                    String parameter= StringUtils.isNotBlank(settings.getCustomParameterName())?settings.getCustomParameterName():settings.getPointName();
                    item.setWarningParameters(parameter);
                }
            });
        }
        return sendMsg;
    }

    public static PushPayload buildPushObject_android_and_ios(String registrationId,String content,String title,Map<String, String> extras) {
        //Map<String, String> extras = new HashMap<String, String>();
        //extras.put("test", "https://community.jiguang.cn/push");

        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                .setAlert(content)
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setTitle(title)
                        .setAlertType(1)
                        .setStyle(1)
                        .setBigText(content)
                        .addExtras(extras).build())
                .addPlatformNotification(IosNotification.newBuilder()
                        .incrBadge(1)
                        .addExtra("extra_key", "extra_value").build())
                .build())
                .setMessage(Message.newBuilder()
                        .setTitle(title)
                        .setMsgContent(content)
                        .addExtras(extras)
                        .build())
                .setOptions(Options.newBuilder()
                    .setApnsProduction(false)
                    .setTimeToLive(43200)
                    .build())
                .build();
    }

    public String getReport(String msgIds) {
        JPushClient jpushClient = new JPushClient(MesJPushConfig.getMasterSecret(), MesJPushConfig.getAppKey());
        ReceivedsResult result=new ReceivedsResult();
        try {
            result = jpushClient.getReceivedsDetail(msgIds);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
        return  result.toString();
    }
}
